var Image = require('../image.js');

module.exports = {
    initialization: initialization
};

function initialization(app) {
    console.log('initialization post-item');

    app.post('/item/getNewPublicList', function(req, res) {
        var data = {};
        data.pageSize = parseInt(req.body.pageSize) || 40;
        data.pageNumber = parseInt(req.body.pageNumber) || 0;
        data.cid = parseInt(req.body.cid) || 0;

        DBOpt.Item.getNewPublicList(data.pageSize, data.pageNumber, data.cid, function(resData) {
            return res.send(resData);
        });
    });

    app.post('/item/search', function(req, res) {
        var data = {};
        data.pageSize = parseInt(req.body.pageSize) || 40;
        data.pageNumber = parseInt(req.body.pageNumber) || 0;
        data.text = req.body.text.trim() || '';

        DBOpt.Item.search(data, function(resData) {
            return res.send(resData);
        });
    });

    app.post('/item/getByIid', function(req, res) {
        var data = {};
        data.iid = parseInt(req.body.iid);
        data.first = !!req.body.first || false;

        DBOpt.Item.getByIid(data.iid, data.first, function(resData) {
            return res.send(resData);
        });
    });

    app.post('/item/add', function(req, res) {
        if (req.session.isLogin !== true) {
            return res.send(ResCode.getCode(100));
        }
        var reqBody = req.body;
        var data = {
            reduction: reqBody.reduction,
            iName: reqBody.iName,
            des: reqBody.des,
            place: reqBody.place,
            cid: reqBody.cid,
            price: reqBody.price,
            uid: req.session.ID
        };
        //check
        if (data.iName.length > 25 || data.des.length > 200 || data.place.length > 50 || !data.cid || !(data.price > 0) || !reqBody.pic0) {
            return res.send(ResCode.getCode(1006));
        }
        Image.save([reqBody.pic0, reqBody.pic1, reqBody.pic2, reqBody.pic3, reqBody.pic4], {
            uid: data.uid
        }, function(pics) {
            data.pic0 = pics[0];
            data.pic1 = pics[1];
            data.pic2 = pics[2];
            data.pic3 = pics[3];
            data.pic4 = pics[4];
            DBOpt.Item.add(data, function(resData) {
                return res.send(resData);
            });
        });
    });
}